﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoneyManagerNET.Presentation.Infrastructure.Collections;
using System.Windows.Data;
using MoneyManagerNET.Presentation.Infrastructure;
using System.Windows.Input;

namespace MoneyManagerNET.Presentation.ViewModel.Base
{


    //for list based windows
    //Model property returns currently selected (may be this is not right)
    public class ListViewModel<T> : ListViewModel where T : class
    {
        ObservableCollection<T> _items;
        public ObservableCollection<T> Items { get { return _items; } set { _items = value; this.OnChange(() => Items); ItemsView = new CollectionView(Items); } }

        public T Selected {
            get { return base.Selected as T; }
            set { base.Selected=value; }
        }

        public ListViewModel(IEnumerable<T> source)
        {
            Items = new ObservableCollection<T>(source);

            this.PropertyChanged += (a, b) =>
            {
                if (b.PropertyName == string.Empty)
                { this.OnChange(() => Items); }
            };

            this._deleteCommand = new DelegateCommand((o) => Delete(),(o)=>Selected!=null);
        }

        DelegateCommand _deleteCommand;
        public ICommand DeleteCommand { get { return _deleteCommand; } }


        internal void Delete()
        {
            int idx = this.Items.IndexOf(Selected);
            this.Items.Remove(Selected);
            App.Storage.Delete(Selected);

            if (idx < Items.Count)
                Selected = Items[idx];
            else
                Selected = null;

            RefreshCommandStatuses();
        } 

        protected override void RefreshCommandStatuses()
        {
            _deleteCommand.RaiseCanExecuteChanged();
        }
    }
}
